package com.brush.app.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.app.domain.AppQuestion;
import com.brush.app.domain.AppSubject;
import com.brush.app.domain.req.question.OptionItem;
import com.brush.app.domain.req.question.QuestionAddReq;
import com.brush.app.domain.req.question.QuestionEditReq;
import com.brush.app.domain.req.question.QuestionReq;
import com.brush.app.domain.resp.question.QuestionDetailResp;
import com.brush.app.domain.resp.question.QuestionResp;
import com.brush.app.service.AppCourseService;
import com.brush.app.service.AppQuestionService;
import com.brush.app.mapper.AppQuestionMapper;
import com.brush.app.service.AppSubjectService;
import com.brush.common.exception.ServiceException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author Administrator
* @description 针对表【app_question(试题表)】的数据库操作Service实现
* @createDate 2024-10-31 16:44:54
*/
@Service
public class AppQuestionServiceImpl extends ServiceImpl<AppQuestionMapper, AppQuestion>
    implements AppQuestionService{

    @Autowired
    private AppCourseService appCourseService;

    @Autowired
    private AppSubjectService appSubjectService;

    @Override
    public PageInfo<QuestionResp> pagination(QuestionReq req) {
        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(()->{

            List<QuestionResp> pagination = this.baseMapper.pagination(req);
            //循环查询课程名称
            pagination.forEach(item->{
               String name=this.appCourseService.getNameById(item.getCourseId());
               item.setCourseName(name);

               //还原正确答案
                if(item.getQuestionType().equals("1")){
                    //单选题答案
                    List<OptionItem> arr=JSONUtil.toList(item.getChooseStr(),OptionItem.class);
                    for(int i=0;i<arr.size();i++){
                        if(arr.get(i).getCorrect()){
                            item.setCorrect(String.valueOf((char)(i+65)));
                            break;
                        }
                    }
                }else if(item.getQuestionType().equals("2")){
                    //多选题答案

                    StringBuilder str=new StringBuilder();
                    List<OptionItem> arr=JSONUtil.toList(item.getChooseStr(),OptionItem.class);
                    for(int i=0;i<arr.size();i++){
                        if(arr.get(i).getCorrect()){
                            str.append(String.valueOf((char)(i+65))).append("、");
                        }
                    }
                    str.deleteCharAt(str.length()-1);

                    item.setCorrect(str.toString());
                }

            });
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(QuestionAddReq req) {
        AppQuestion entity=new AppQuestion();
        BeanUtils.copyProperties(req,entity);

        entity.setDelFlag("0");
        entity.setViewsNum(0);
        entity.setLikeNum(0);
        entity.setErrorsNum(0);

        //清除单选的答案
        if(req.getQuestionType().equals("1")){
            String temp=entity.getCorrect().trim();
            if(StrUtil.isBlank(temp)){
                throw new ServiceException("单选题请先设置答案");
            }

            entity.setCorrect(null);
            //把答案赋值给选中的项,以便于后续随机打乱顺序用
           for(int i=0;i<req.getChoose().size();i++){
               OptionItem item=req.getChoose().get(i);
               String upperLetter=String.valueOf((char)(i+65));
               if(upperLetter.equals(temp)){
                   item.setCorrect(true);
                   break;
               }
           }
        }else if(req.getQuestionType().equals("2")){
            //多选
            if(req.getCorrectMutil()==null || req.getCorrectMutil().length==0){
                throw new ServiceException("多选题请先设置答案");
            }
            entity.setCorrect(null);

           List<String> arr= Arrays.asList(req.getCorrectMutil());
            for(int i=0;i<req.getChoose().size();i++){
                OptionItem optionItem=req.getChoose().get(i);
                String upperLetter=String.valueOf((char)(i+65));
                for(String answer:arr){
                    if( upperLetter.equals(answer)){
                        optionItem.setCorrect(true);
                    }
                }
            }
        }else{
            if(StrUtil.isBlank(entity.getCorrect())){
                throw new ServiceException("简答题请先设置答案");
            }
        }

        if(!req.getChoose().isEmpty()){
            String choose= JSONUtil.toJsonStr(req.getChoose());
            entity.setChoose(choose);
        }

        boolean result=this.save(entity);

        //更新课程的题目数量
        result=appCourseService.updateQuestionNum(req.getCourseId(),1);

        return result;
    }

    /**
     * 查询题目详情
     * @param id
     * @return
     */
    @Override
    public QuestionDetailResp findById(Long id) {
        AppQuestion db=this.getById(id);

        QuestionDetailResp resp=new QuestionDetailResp();
        BeanUtils.copyProperties(db,resp);

        AppSubject dbSubject=this.appSubjectService.getById(db.getSubjectId());
        resp.setSubjectName(dbSubject.getName());

        String name=this.appCourseService.getNameById(db.getCourseId());
        resp.setCourseName(name);

        //还原选中的科目
        Long[] cascader=this.appCourseService.getParentsId(db.getCourseId());
        resp.setCascaderCourse(cascader);

        //把选项转换成对象
        if(StrUtil.isNotBlank(db.getChoose())){
            List<OptionItem> list=JSONUtil.toList(db.getChoose(),OptionItem.class);
            resp.setChoose(list);
        }
        //默认多选题为空
        resp.setCorrectMutil(new String[0]);

        //多选题
        if(db.getQuestionType().equals("2")){
             List<String> arr=new ArrayList<>();
             for(int i=0;i<resp.getChoose().size();i++){
                 OptionItem item=resp.getChoose().get(i);
                 if(item.getCorrect()){
                     //把它转为大小字母
                     arr.add(String.valueOf((char)(i+65)));
                 }
             }
             resp.setCorrectMutil(arr.toArray(new String[0]));

        }else if ( db.getQuestionType().equals("1")){
          // 单选题
            for(int i=0;i<resp.getChoose().size();i++){
                OptionItem item=resp.getChoose().get(i);
                if(item.getCorrect()){
                    //把它转为大小字母
                    resp.setCorrect(String.valueOf((char)(i+65)));
                    break;
                }
            }
        }

        return resp;
    }

    /**
     * 修改题目
     * @param req
     * @return
     */
    @Override
    public boolean edit(QuestionEditReq req) {
        AppQuestion entity=new AppQuestion();
        //复制属性的时候，要取消下面这几列的操作
        BeanUtils.copyProperties(req,entity,"viewsNum","likeNum","errorsNum");

        //还原选项中正确答案
        //单选
        if(req.getQuestionType().equals("1")){
            //正确的值
            String temp=entity.getCorrect().trim();

            if(StrUtil.isBlank(temp)){
                throw new ServiceException("单选题请先设置答案");
            }

            entity.setCorrect(null);
            //把答案赋值给选中的项,以便于后续随机打乱顺序用
            //取消原来的选中的答案设定为false
            req.getChoose().forEach(item->item.setCorrect(false));

            for(int i=0;i<req.getChoose().size();i++){
                OptionItem item=req.getChoose().get(i);
                String upperLetter=String.valueOf((char)(i+65));
                if(upperLetter.equals(temp)){
                    item.setCorrect(true);
                    break;
                }
            }

        }else if(req.getQuestionType().equals("2")){
            //多选
            if(req.getCorrectMutil()==null || req.getCorrectMutil().length==0){
                throw new ServiceException("多选题请先设置答案");
            }
            entity.setCorrect(null);

            //设定原有选项为false
            req.getChoose().forEach(item->item.setCorrect(false));

            List<String> arr= Arrays.asList(req.getCorrectMutil());
            for(int i=0;i<req.getChoose().size();i++){
                OptionItem optionItem=req.getChoose().get(i);
                String upperLetter=String.valueOf((char)(i+65));

                for(String answer:arr){
                    if( upperLetter.equals(answer)){
                        optionItem.setCorrect(true);
                        break;
                    }
                }
            }
        }

        //设定选项
        if(!req.getChoose().isEmpty()){
            String choose= JSONUtil.toJsonStr(req.getChoose());
            entity.setChoose(choose);
        }


        return this.updateById(entity);
    }
}




